jQuery.ajaxSetup({
    async:true
});

var firstLoad = true;
var current_page = 0;

$(document).ready(function () {
    $("#result").tabs();  
    
    if(settings.use_facets == false){
        $("#facets").hide();
    }
    
    $( "#result" ).bind( "tabsselect", function(event, ui) {
        //console.log(ui);
        $.bbq.pushState({
            tab : ui.tab.href.substring(ui.tab.href.indexOf('#')+1)
        });
    });

    populateSeries();
    
    updateUI();
    
    $('#search-form').submit(function(event) {	
        event.preventDefault();
	
        preformSearch(0, 'all');

        return false;
    });
    
    //language swith-links
    $("#languages a").click( function(){
        var new_lang = $(this).data("mode");
            if(settings.active_lang != new_lang){
            $.bbq.pushState({
                lang : new_lang
            });
            settings.active_lang = new_lang;

            getFacets();
            updateUI();
        } 
    });  
 
    //get current state and select tab
    if($.bbq.getState("tab")){
        $("#result").tabs('select', '#' + $.bbq.getState("tab"));
    }
 
    if($.bbq.getState("q")){
        $("#search").val($.bbq.getState("q"));
    }
    
    if($.bbq.getState("advanced") == 'active'){
        $(".heading").trigger('click');
    }
    
    activateAutocomplete('title');
    activateAutocomplete('creator');
    
    preformSearch(0, 'all');
});

function updateUI(){
    settings.active_lang = $.bbq.getState("lang") || settings.default_lang;
    $("[data-localize]").localize("locale", {
        packages : ["locale"],
        pathPrefix : "translations",
        language : settings.active_lang
    });    
    
    setActiveLang(settings.active_lang);
}

/**
* run the search query against the database
* @param {Integer} start index for start page
* @param {String} type type of search (study, question, variable or all)
*/
function preformSearch(start, type){
    $('#result').show('fast');
  
    var query_type = 'study,question,variable';
    
    if(query_type.indexOf(type) >= 0){
        query_type = type;
    }
  
    var q = $.trim($("#search").val());
        
    $.bbq.pushState({
            q : q
    });
  
    switch(type){
        case 'all':
            $('.study-tab a').addClass('loading');
            $('.question-tab a').addClass('loading');
            $('.variable-tab a').addClass('loading');
            //get facets for the current search
            getFacets();
            break;
        default:
            $('.'+type+'-tab a').addClass('loading');
    }
    
    var data = {
        type:type,
        start:start, 
        records:settings.items_per_page,
        type:query_type,
        format:'json'
    };
    
    var facets = updateFacets();
    data = merge_options(data, facets);
    
    if(q)
        data['q'] = q;

    if($("#series").val())
        data['series'] = $("#series").val().join(',');



    $.ajax({
        url: settings.backend + '/ws/search.xql',
        dataType: 'jsonp',
        data: data,
        success: function(result){
  
            //console.log('search done for '+type);

            switch(type){
                case 'study':
                    studySearchDone(result.studies);
                    break;
                
                case 'question':
                    questionSearchDone(result.questions);
                    break;

                case 'variable':
                    variableSearchDone(result.variables);
                    break;
  
                default:
                    studySearchDone(result.studies);
                    questionSearchDone(result.questions);
                    variableSearchDone(result.variables);
                    buildPager('study',     result.studies.hits);
                    buildPager('question',  result.questions.hits);
                    buildPager('variable',  result.variables.hits);
                    
                    //diable tabs with not hits
                    var disabled = new Array();
                    if(result.studies.hits == 0)
                        disabled.push(0);
                    if(result.questions.hits == 0)
                        disabled.push(1);
                    if(result.variables.hits == 0)
                        disabled.push(2);     
                    $("#result").tabs({ disabled: disabled }); 
            }
            
            
            
            setActiveLang(settings.active_lang);
            
            //highlight
            q = q.replace(/\AND/g,' ');
            q = q.replace(/\OR/g,' ');
            q = q.replace(/\NOT/g,' ');
            q = q.replace(/\*/g,' ');
            q = q.replace(/\(/g,' ');
            q = q.replace(/\)/g,' ');

            q = q.split(" ");

            $(".lang-strings").highlight(q);
            
        }
    });
}

/**
* builds the pager
* @param {String} type type of pager (study, question, variable)
* @param {Integer} number_of_hits number of hits per page
*/
function buildPager(type, number_of_hits){	
    
    if(number_of_hits > settings.items_per_page ){
        
        $("#"+type+"-pagination").show();
        $("#"+type+"-pagination").pagination(
            number_of_hits, 
            {
                items_per_page:settings.items_per_page, 
                callback:paginationClick,
                next_text: $.format('<span data-localize="next">%s</span>', [getLocaleString('next')]),
                prev_text: $.format('<span data-localize="prev">%s</span>', [getLocaleString('prev')]),
                link_to:"#",
                //current_page: $.bbq.getState(type+"_page"),  <-strange bug in question page
                num_display_entries: 10,
                num_edge_entries:2,
                ellipse_text: '..'
            });
        updateUI();
    }else{
        $("#"+type+"-pagination").hide();
    }
}

/**
* handels click on the pagination bars
* @param {Integer} new_page_index new_page index for new page
* @param {Object} pagination_container contaioner for the pager
* @return {Boolean} always false
*/
function paginationClick(new_page_index, pagination_container) {	
    if(new_page_index != current_page){
        var q           = $('input[name=s]').val();

        var start 	= new_page_index * settings.items_per_page;
        var end 	= (start + settings.items_per_page);

        current_page = new_page_index;
        
        var type = $(pagination_container).attr('id').replace('-pagination','');

        switch(type){
            case 'study':
                $.bbq.pushState({study_page : current_page});
                break;            
            case 'question':
                $.bbq.pushState({question_page : current_page});
                break;
           case 'variable':
                $.bbq.pushState({variable_page : current_page});
                break;                
        }

        //console.log(type+' : '+start+'-'+end);
        preformSearch(start, type);
    }
    //console.log('new page: '+new_page_index);
    return false;
}

/**
* populates the series filter dialog
*/
function populateSeries(){
    $.ajax({
        url: settings.backend+'/ws/series.xql?',
        dataType: "jsonp",
        data:{
            format:'json',
            lang:settings.default_lang
        },
        success: function(data){
            $.each(data.series, function(key, val) {
                $('#series').append($("<option></option>").
                    attr("value",val.id).
                    text(val.name)); 
            });
            $("#series").multiselect(
            {
                selectedText:     $.format('# <span data-localize="of">%s</span> # <span data-localize="selected">%s</span>', [getLocaleString('of'), getLocaleString('selected')]),
                noneSelectedText: $.format('<span data-localize="select">%s</span> <span data-localize="series">%s</span>', [getLocaleString('select'), getLocaleString('series')]),
                checkAllText:     $.format('<span data-localize="check_all">%s</span>', [getLocaleString('check_all')]),
                uncheckAllText:   $.format('<span data-localize="uncheck_all">%s</span>', [getLocaleString('uncheck_all')])
            }
            ).multiselectfilter({
                label: $.format('<span data-localize="filter">%s</span>:', [getLocaleString('filter')]),
                placeholder: getLocaleString('enter_keywords')
            });
                
            updateUI();
        }
    });
    $(".heading").click(function(){
        $(this).next(".content").slideToggle(500);	
        $(this).toggleClass('header-open');
        
        if($.bbq.getState("advanced") == 'active'){
            $.bbq.removeState(['advanced']);
        }else{
            $.bbq.pushState({advanced : 'active'});
        }
    });
    
    $(".content").hide();
}

function setActiveLang(lang){
    var fields = $('.lang-strings');
    $.each(fields, function(i,field){
        //console.log($(field).children('.'+lang));
        if($(field).children('span.'+lang).length == 1){
            //console.log('found');
            $(field).children().hide();
            $(field).children('.'+lang).css('font-style', '');
            $(field).children('.'+lang).show();
        }else{
            $(field).find(">:first-child").css('font-style', 'italic');
            $(field).find(">:first-child").show();
            //console.log('not found');
            //console.log($(field).find(">:first-child"));
        }
        
    });
}

function getFacets(){
    if(settings.use_facets ==false)
        return;
    
    var q =$("#search").val();
    var data = {
        q:q, 
        lang:settings.active_lang,
        type:'facet',
        format:'json'
    };

    var facets = updateFacets();
    data = merge_options(data, facets);

    if($("#series").val())
        data['series'] = $("#series").val().join(',');

    $.ajax({
        url: settings.backend + '/ws/search.xql',
        dataType: 'jsonp',
        data: data,
        success: function(result){
            var content = '';
            $.each(result.facets.facet, function(i,facet){
                content += $.format('<ul><li class="facet" data-localize="%s">%s</li><ul>', [facet.label, getLocaleString(facet.label)]);
                
                if(facet.term instanceof Array){
                    $.each(facet.term, function(j,term){
                        if(term['#text']){
                            var termLabel = term['#text'];
                            
                            var c = "";
                            if(settings.facets[facet.label] instanceof Array && jQuery.inArray(termLabel, settings.facets[facet.label]) >= 0)
                                c = "selected";
                            
                            content += $.format('<li class="term"><a href="#" title="%s" data-facet="%s" class="%s">%s<span class="docs">(%s)</span></a></li>', [termLabel, facet.label, c, termLabel.ellipsisText('end',settings.facet_term_max_length), term.docs]);
                        }
                    });
                }else if(facet.term && facet.term['#text']){
                    var termLabel = facet.term['#text'];

                    var c = "";
                    if(settings.facets[facet.label] instanceof Array && jQuery.inArray(termLabel, settings.facets[facet.label]))
                        c = "selected";
                    
                    content += $.format('<li class="term"><a href="#" title="%s" data-facet="%s" class="%s">%s<span class="docs">(%s)</span></a></li>', [termLabel, facet.label, c, termLabel.ellipsisText('end',settings.facet_term_max_length), facet.term.docs]);
                }else{
                    content += $.format('<li data-localize="no_hits">%s</li>', [getLocaleString('no_hits')]);
                }
                content += '</ul></ul>';
            });
            $("#facets-content").html(content);
            
            //add/remove the selected term to the global values
            $("#facets-content a").click(function (e){
                $(this).toggleClass('selected');
                
                var facet = $(this).attr("data-facet");
                var term  = $(this).attr("title");
                
                if(settings.facets[facet] instanceof Array == false)
                    settings.facets[facet] = new Array();
                
                if($(this).hasClass('selected')){
                    if(jQuery.inArray(term, settings.facets[facet]) < 0){
                        settings.facets[facet].push(term);
                    }
                }else{                    
                    settings.facets[facet].splice( $.inArray(term,settings.facets[facet]) ,1 );
                    if(settings.facets[facet].length == 0){
                        delete settings.facets[facet];
                        $.bbq.removeState(facet);
                    }
                }
                updateFacets();
                
                e.preventDefault();
            });
            updateFacets();
        }
    });
}

function updateFacets(){
    var facets = {};
    $.each(settings.facets, function(facet, terms){
        facets[facet] = terms.join('|');
        var temp = {};
        temp[facet] = facets[facet];
        $.bbq.pushState(temp);
    });
    
    return facets;
}

function activateAutocomplete(field){
    $('input[name='+field+']').autocomplete({
        source: function( request, response ) {
            $.ajax({
                url: settings.backend+'/ws/autocomplete.xql?',
                dataType: "jsonp",
                data: {
                        type: field,
                        format: "json",
                        lang: settings.active_lang,
                        q: request.term
                },
                success: function( data ) {
                    response(data[1]);
                }
            });
        },
        minLength: 2
    });
}

getLocaleString = function(key){
    if(!$.localize.data){
        return;
    }

    var output = $.localize.data.locale[key] || $.localize.data.sb[key];
    if(output == null && key != null) 
        return key;

    return output;
};

String.prototype.ellipsisText = function(location, maxCharacters) {
    var text = this;
    if (this.length > 0 && this.length > maxCharacters) {
        if (typeof (location) == 'undefined') location = 'end';
        switch (location) {
            case 'center':
                var center = (maxCharacters / 2);
                text = this.slice(0, center) + '...' + this.slice(-center);
                break;
            case 'end':
                text = this.slice(0, maxCharacters - 3) + '...';
                break;
        }
    }
    return text;
}

/**
 * Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
 * @param obj1
 * @param obj2
 * @returns obj3 a new object based on obj1 and obj2
 */
function merge_options(obj1,obj2){
    var obj3 = {};
    for (var attrname in obj1) { obj3[attrname] = obj1[attrname]; }
    for (var attrname in obj2) { obj3[attrname] = obj2[attrname]; }
    return obj3;
}
